<template>
  <van-tabbar v-model="selectedTab" fixed @change="onChange">
    <van-tabbar-item
      v-for="(item, i) of tabbarItems"
      :key="i"
      :icon="item.icon"
    >
      {{ item.title }}
    </van-tabbar-item>
  </van-tabbar>
</template>

<script>
export default {
  data() {
    return {
      selectedTab: 0, // 当前选中的 TabBar 索引
      tabbarItems: [
        { title: "首页", routeName: "home", icon: "home-o" },
        { title: "商品", routeName: "product", icon: "gift-o" },
        { title: "购物车", routeName: "shopcart", icon: "shopping-cart-o" },
        { title: "我的", routeName: "user", icon: "user-o" },
      ],
    };
  },
  watch: {
    // 监听路由变化，同步更新 selectedTab
    $route(to) {
      const currentRouteName = to.name;
      const index = this.tabbarItems.findIndex(
        (item) => item.routeName === currentRouteName
      );
      if (index !== -1) {
        this.selectedTab = index; // 更新选中项
      }
    },
  },
  methods: {
    onChange(index) {
      // 底部导航栏切换时，跳转到对应路由
      this.$router.push({ name: this.tabbarItems[index].routeName });
    },
  },
};
</script>